//
//  AppDelegate.h
//  JCSwizzle
//
//  Created by chun on 2018/5/23.
//  Copyright © 2018年 JC. All rights reserved.
//

#import "NSObject+Swizzle.h"
#import <objc/runtime.h>

static char *enterCountKey = "enterCountKey";

@implementation NSObject (Swizzle)

+ (BOOL)exchangeOriginMethod:(SEL)originSel
                   newMethod:(SEL)newSel {
    
    Method originMethod = class_getInstanceMethod(self, originSel);
    Method newMethod = class_getInstanceMethod(self, newSel);

    if (!class_addMethod([self class], newSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        method_exchangeImplementations(originMethod, newMethod);
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)replaceOriginMethod:(SEL)originSel
                  newMethod:(SEL)newSel {
    Method originMethod = class_getInstanceMethod(self, originSel);
    Method newMethod = class_getInstanceMethod(self, newSel);

    if (!class_addMethod([self class], newSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(self, newSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
        
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)addMethod:(SEL)newSel {
    Method newMethod = class_getInstanceMethod(self, newSel);    
    if (class_addMethod([self class], newSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        return YES;
    } else {
        return NO;
    }
}

- (void)setEnterCount:(NSInteger)enterCount {
    NSString *countString = [NSString stringWithFormat:@"%ld", enterCount];
    objc_setAssociatedObject(self, enterCountKey, countString, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSInteger)enterCount {
    return  [objc_getAssociatedObject(self, enterCountKey) integerValue];
}
@end
